#include "linked_list.h"

LinkedList* create_linked_list() {
	LinkedList* list = (LinkedList*)calloc(1, sizeof(LinkedList));
	ERROR_CHECK(list, NULL, "calloc failed in create_linked_list.\n");

	return list;
}
bool add_behind_tail(LinkedList* list, DataType data) {
	Node* node = (Node*)calloc(1, sizeof(Node));
	if (node == NULL) {
		printf("error: calloc failed in add_before_head.\n");
		return 0;
	}
	node->data = data;

	// 尾插	
	if (list->head == NULL) {
		list->head = list->tail = node;
	}else {
		list->tail = list->tail->next = node;
	}
	list->size++;
	return 1;
}
void destroy_linked_list(LinkedList* list) {

	Node* curr = list->head;
	while (curr) {
		Node* t = curr;
		free(t);
		curr = curr->next;
	}

	free(list);
}
bool delete_node_by_data(LinkedList* list, DataType data) {
	Node* predecessor = 0;
	Node* curr = list->head;
	for (; curr && curr->data != data; predecessor = curr, curr = curr->next);

	if (curr) {
		if (curr == list->head) {
			list->head = list->head->next;
		}else{
			predecessor->next = curr->next;
		}

		if (curr == list->tail) {
			list->tail = predecessor;
		}
		list->size--;
		free(curr);
		return 1;
	}
	return 0;
}